<!-- components/GoodsList.vue -->
<script setup>
import { ref, watchEffect } from 'vue'
import { getProductListAPI } from '@/apis/product'

const props = defineProps({
  categoryId: {
    type: [String, Number],
    required: true
  }
})

const loading = ref(false)
const error = ref(null)
const productList = ref([])
const pagination = ref({
  page: 1,
  size: 10,
  total: 0
})

const getProducts = async () => {
  try {
    loading.value = true
    const res = await getProductListAPI(props.categoryId, pagination.value.page, pagination.value.size)
    productList.value = res.data.list
    pagination.value.total = res.data.total
  } catch (e) {
    error.value = e.message || '获取商品失败'
  } finally {
    loading.value = false
  }
}

watchEffect(() => {
  if (props.categoryId) {
    getProducts()
  }
})
</script>

<template>
  <div class="goods-list">
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <template v-else>
      <GoodsItem
          v-for="item in productList"
          :key="item.id"
          :goods="item"
      />
      <el-pagination
          v-model:current-page="pagination.page"
          :page-size="pagination.size"
          :total="pagination.total"
          layout="prev, pager, next"
          @current-change="getProducts"
      />
    </template>
  </div>
</template>